<template>
    <view class="marquee-container" v-show="visible">
        <view id="marquee" class="marquee-content" :style="marqueeStyle" @animationend="handleAnimationEnd">
            <slot>{{ text }}</slot>
        </view>
    </view>
</template>

<script>
export default {
    name: 'Marquee',
    props: {
        // 滚动文本内容
        text: {
            type: String,
            default: ''
        },
        // 滚动速度（秒）
        duration: {
            type: Number,
            default: 10
        },
        // 循环次数，-1为无限循环
        loop: {
            type: Number,
            default: -1
        },
        // 是否自动开始
        autoStart: {
            type: Boolean,
            default: true
        }
    },
    data() {
        return {
            visible: true,
            currentLoop: 0
        };
    },
    computed: {
        marqueeStyle() {
            return {
                animationDuration: `${this.duration}s`,
                animationIterationCount: this.loop === -1 ? 'infinite' : this.loop
            };
        }
    },
    mounted() {
        if (this.autoStart) {
            this.start();
        }
    },
    methods: {
        start() {
            this.animate(
                '#marquee',
                [
                    { transform: 'translateX(0)'},
                    { transform: 'translateX(-100%)'},
                ],
                5000,
                function () {
                    this.clearAnimation('#marquee', { opacity: true, rotate: true }, function () {
                        console.log('清除了#container上的opacity和rotate属性');
                    });
                }.bind(this)
            );
        },
        stop() {
            this.visible = false;
            this.currentLoop = 0;
        },
        handleAnimationEnd() {
            this.currentLoop++;
            if (this.loop !== -1 && this.currentLoop >= this.loop) {
                this.stop();
                this.$emit('complete');
            }
        }
    }
};
</script>

<style lang="scss" scoped>
.marquee-container {
    width: 100%;
    overflow: hidden;
    background-color: rgba(91, 103, 202, 0.1);
    padding: 8rpx 20rpx;
}

.marquee-content {
    display: inline-block;
    white-space: nowrap;
    animation: marquee linear;
    color: $brand-color;
    font-size: 24rpx;
}

@keyframes marquee {
    from {
        transform: translateX(0);
    }
    to {
        transform: translateX(-100%);
    }
}
</style>
